package com.rds.material.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.rds.common.api.material.domain.RdaPart;
import com.rds.common.api.material.domain.RdaPartDynamicattribute;
import com.rds.common.core.controller.BaseController;
import com.rds.common.core.domain.AjaxResult;
import com.rds.common.core.page.TableDataInfo;
import com.rds.common.utils.SecurityUtils;

import com.rds.material.service.IRdaPartDynamicattributeService;
import com.rds.material.service.IRdaPartService;
import com.rds.material.service.IRdaPartsRelService;
import com.rds.material.utils.WorkspaceUtils;
import com.rds.system.domain.RdaType;
import com.rds.system.domain.RdaTypeAttribute;
import com.rds.system.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

@RestController
@RequestMapping("/pms/materialType")
public class MaterialTypeController extends BaseController {

    @Autowired
    private IRdaTypeService rdaTypeService;

    @Autowired
    private IRdaPartDynamicattributeService rdaMaterialDynamicattributeService;

    @Autowired
    private IRdaTypeAttributeService rdaTypeAttributeService;

    @Autowired
    private IRdaPartsRelService rdaPartsRelService;

    @Autowired
    private IRdaTableColumnService rdaTableColumnService;

    @Autowired
    private IRdaFormDetailsService rdaFormDetailsService;

    @Autowired
    private IRdaPartService rdaMaterialService;

    @Autowired
    private IRdaPolicyService rdaPolicyService;

    @Autowired
    private IRdaStateService rdaStateService;

    /**
     * 查询物料分类
     */
    @PreAuthorize("@ss.hasPermi('pms:materialType:materialTypeList')")
    @GetMapping("/materialTypeList")
    public TableDataInfo materialTypeList(){
        startPage();
        List<RdaType> list = rdaTypeService.selectRdaTypeLowerList("物料管理超类");
        return getDataTable(list);
    }

    /**
     * 根据分类类型查询物料属性
     */
    @PreAuthorize("@ss.hasPermi('pms:materialType:getWftypeid')")
    @GetMapping("/getWftypeid")
    public TableDataInfo getInfo( String wftypeid){
        Map<String,Object> dmap= WorkspaceUtils.getTypePolicyStates("partSeries","1",rdaTypeService,rdaPolicyService,rdaStateService);
        Map<String,Long> dtypeid=(Map<String,Long>)dmap.get("Typeid");
        Long typeid=dtypeid.get("partSeries");

        List<RdaPart> rdaPartList=rdaMaterialService.selectRdaPartTreeSubordinate(Long.parseLong(wftypeid),typeid);
        Long ids[]=new Long[rdaPartList.size()+1];
        ids[0]=Long.valueOf(wftypeid);
        for(int i=0;i<rdaPartList.size();i++){
            ids[i+1]=rdaPartList.get(i).getId();
        }
        startPage();
       /* RdaPartDynamicattribute rdaPartDynamicattribute =new RdaPartDynamicattribute();
        rdaPartDynamicattribute.setTypeid(Long.valueOf(wftypeid));
        rdaPartDynamicattribute.setIsDel(0);
        return getDataTable(rdaMaterialDynamicattributeService.selectRdaPartDynamicattributeList(rdaPartDynamicattribute));*/
        return getDataTable(rdaMaterialDynamicattributeService.selectRdaPartDynamicattributeByInIds(ids));
    }

    /**
     * 新增物料类型字段属性
     */
    @PreAuthorize("@ss.hasPermi('pms:materialType:addPartsAttribute')")
    @PostMapping("/addPartsAttribute")
    @Transactional
    public AjaxResult addAttribute(@RequestBody RdaTypeAttribute rdaTypeAttribute, ServletRequest request)
    {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        String wftypeid=httpRequest.getParameter("wftypeid");
        Integer typeid=Integer.parseInt(wftypeid);
        Long userId = SecurityUtils.getUserId();
        rdaTypeAttribute.setStatus(2);
        rdaTypeAttribute.setUpdateBy(String.valueOf(userId));
        rdaTypeAttribute.setTypeid(typeid);
        int row=rdaTypeAttributeService.insertRdaTypeAttribute(rdaTypeAttribute);
        return toAjax(row);
    }

    /**
     * 新增物料属性
     */
    @PreAuthorize("@ss.hasPermi('pms:materialType:addDynamicattribute')")
    @PostMapping("/addDynamicattribute")
    @Transactional
    public AjaxResult addDynamicattribute(@RequestBody RdaPartDynamicattribute rdaPartDynamicattribute){
        Long userId = SecurityUtils.getUserId();
        rdaPartDynamicattribute.setStatus("1");
        rdaPartDynamicattribute.setUpdateBy(String.valueOf(userId));
        rdaPartDynamicattribute.setTypeid(rdaPartDynamicattribute.getParentid());
        rdaPartDynamicattribute.setOwnerid(SecurityUtils.getUserId());
        int rows=rdaMaterialDynamicattributeService.insertRdaPartDynamicattribute(rdaPartDynamicattribute);
       /* ArrayList<Integer> maxtSort=new ArrayList<Integer>();
        List<RdaTableColumn> rdaTableColumnList=rdaTableColumnService.selectByConfigName("materialDetailed");
        rdaTableColumnList.forEach((RdaTableColumn rdaTableColumn)->{
            maxtSort.add(rdaTableColumn.getSort());
        });
        if(maxtSort!=null && maxtSort.size()!=0){
            Integer sort=Collections.max(maxtSort);
            RdaTableColumn rdaTableColumn=new RdaTableColumn();
            rdaTableColumn.setTableid(rdaTableColumnList.get(0).getTableid());
            rdaTableColumn.setName(rdaPartDynamicattribute.getDescription());
            rdaTableColumn.setDescription(rdaPartDynamicattribute.getDescription());
            rdaTableColumn.setProp(rdaPartDynamicattribute.getAttributeName());
            rdaTableColumn.setAlign("center");
            rdaTableColumn.setSort(sort+10);
            rdaTableColumnService.insertRdaTableColumn(rdaTableColumn);
        }
        ArrayList<Integer> maxtSort2=new ArrayList<Integer>();
        List<RdaFormDetails> rdaFormDetailsList=rdaFormDetailsService.selectByConfigName("add_material");
        rdaFormDetailsList.forEach((RdaFormDetails rdaFormDetails)->{
            maxtSort2.add(rdaFormDetails.getSort());
        });
        if(maxtSort2!=null && maxtSort2.size()!=0){
            Integer sort=Collections.max(maxtSort2);
            RdaFormDetails rdaFormDetails=new RdaFormDetails();
            rdaFormDetails.setFormid(rdaFormDetailsList.get(0).getFormid());
            rdaFormDetails.setName(rdaPartDynamicattribute.getDescription());
            rdaFormDetails.setDescription(rdaPartDynamicattribute.getDescription());
            rdaFormDetails.setProp(rdaPartDynamicattribute.getAttributeName());
            rdaFormDetails.setComponentType("el-input");
            rdaFormDetails.setSort(sort+10);
            rdaFormDetailsService.insertRdaFormDetails(rdaFormDetails);
        }*/
        return toAjax(rows);
    }

    /**
     * 删除物料属性
     */
    @PreAuthorize("@ss.hasPermi('pms:materialType:deletematerialDynamicattribute')")
    @DeleteMapping("/{ids}")
    @Transactional
    public AjaxResult deleteWorkflowDynamicattribute(@PathVariable Long[] ids){
        return toAjax(rdaMaterialDynamicattributeService.deleteRdaPartDynamicattributeByIds(ids));
    }

    /**
     * 获取物料属性详细信息
     */
    @PreAuthorize("@ss.hasPermi('pms:materialType:dynamicattributeList')")
    @GetMapping(value = "dynamicattributeList/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(rdaMaterialDynamicattributeService.selectRdaPartDynamicattributeById(id));
    }
    /**
     * 修改物料属性
     */
    @PreAuthorize("@ss.hasPermi('pms:materialType:dynamicattributeList')")
    @PutMapping("/dynamicattributeList")
    @Transactional
    public AjaxResult modifyWorkflowList(@RequestBody RdaPartDynamicattribute rdaPartDynamicattribute){
        return AjaxResult.success(rdaMaterialDynamicattributeService.updateRdaPartDynamicattribute(rdaPartDynamicattribute));
    }

    /**
     * 物料动态属性table查询
     */
    @PreAuthorize("@ss.hasPermi('pms:materialType:dynamicAttributeTable')")
    @GetMapping(value = "dynamicAttributeTable/{id}")
    public JSONObject dynamicAttributeTable(@PathVariable("id") Long id)
    {
        JSONObject jsonobj = new JSONObject();
        ArrayList<String> jsonList=new ArrayList<String>();
        Map<String,Object> dmap= WorkspaceUtils.getTypePolicyStates("partSeries","1",rdaTypeService,rdaPolicyService,rdaStateService);
        Map<String,Long> dtypeid=(Map<String,Long>)dmap.get("Typeid");
        Long typeid=dtypeid.get("partSeries");

        List<RdaPart> rdaPartList=rdaMaterialService.selectRdaPartTreeSubordinate(id,typeid);
        Long ids[]=new Long[rdaPartList.size()+1];
        ids[0]=Long.valueOf(id);
        for(int i=0;i<rdaPartList.size();i++){
            ids[i+1]=rdaPartList.get(i).getId();
        }
        List<RdaPartDynamicattribute> list=rdaMaterialDynamicattributeService.selectRdaPartDynamicattributeByInIds(ids);
        list.forEach((RdaPartDynamicattribute t)->{
            StringBuilder attribute=new StringBuilder();
            attribute.append("{name:\""+t.getDescription()+"\",prop:\""+t.getAttributeName()+"\"");
            attribute.append(",description:\""+t.getDescription()+"\",align:\"center\",width:\"\"");
            if(t.getLevel()!=null){
                attribute.append(",className:\"\",propType:\"text\",sort:"+(t.getLevel()+100)+",fullEdit:false");
            }else{
                attribute.append(",className:\"\",propType:\"text\",sort:"+(100)+",fullEdit:false");

            }
            attribute.append(",showOverflow:true,show:true,sortable:false,status:1");
            attribute.append("}");
            jsonList.add(attribute.toString());
        });
        System.out.println("jsonList===="+jsonList);
        String jarr = JSON.toJSONString(jsonList);
        com.alibaba.fastjson.JSONArray jsonArray = com.alibaba.fastjson.JSONArray.parseArray(jarr);
        List<Object> lists = JSON.parseArray(jsonArray.toJSONString(), Object.class);
        List<com.alibaba.fastjson.JSONObject> result = new ArrayList<>();
        for (Object obj : lists) {
            com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(obj.toString());
            result.add(jsonObject);
        }
        jsonobj.put("rows", result);
        jsonobj.put("total", rdaPartList.size());
        return jsonobj;
    }

    /**
     * 物料动态属性table查询
     */
    @PreAuthorize("@ss.hasPermi('pms:materialType:dynamicAttributeAddForm')")
    @GetMapping(value = "dynamicAttributeAddForm/{id}")
    public JSONObject dynamicAttributeAddForm(@PathVariable("id") Long id)
    {
        JSONObject jsonobj = new JSONObject();
        ArrayList<String> jsonList=new ArrayList<String>();
        Map<String,Object> dmap= WorkspaceUtils.getTypePolicyStates("partSeries","1",rdaTypeService,rdaPolicyService,rdaStateService);
        Map<String,Long> dtypeid=(Map<String,Long>)dmap.get("Typeid");
        Long typeid=dtypeid.get("partSeries");

        List<RdaPart> rdaPartList=rdaMaterialService.selectRdaPartTreeSubordinate(id,typeid);
        Long ids[]=new Long[rdaPartList.size()+1];
        ids[0]=Long.valueOf(id);
        for(int i=0;i<rdaPartList.size();i++){
            ids[i+1]=rdaPartList.get(i).getId();
        }
        List<RdaPartDynamicattribute> list=rdaMaterialDynamicattributeService.selectRdaPartDynamicattributeByInIds(ids);
        list.forEach((RdaPartDynamicattribute t)->{
            StringBuilder attribute=new StringBuilder();
            attribute.append("{abreast:false,componentType:\"el-input\"");
            attribute.append(",editable:true,name:\""+t.getDescription()+"\",prop:\""+t.getAttributeName()+"\"");
            attribute.append(",required:false,sort:"+(t.getLevel()+100)+"");
            attribute.append(",status:\""+t.getStatus()+"\"");
            attribute.append("}");
            jsonList.add(attribute.toString());
        });
        String jarr = JSON.toJSONString(jsonList);
        com.alibaba.fastjson.JSONArray jsonArray = com.alibaba.fastjson.JSONArray.parseArray(jarr);
        List<Object> lists = JSON.parseArray(jsonArray.toJSONString(), Object.class);
        List<com.alibaba.fastjson.JSONObject> result = new ArrayList<>();
        for (Object obj : lists) {
            com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(obj.toString());
            result.add(jsonObject);
        }
        jsonobj.put("data", result);
        jsonobj.put("total", rdaPartList.size());
        return jsonobj;
    }
}
